<?php 
namespace app\admin\controller;

use think\Controller;
use think\Request;
use think\Exception;
use think\Db;
use app\common\model\admin\AdminUser;
use app\common\controller\Log;

class Login extends Controller
{
	/**
	 * 检查登录状态
	 * @return unknown
	 */
	public function checkLogin()
	{
		if(session('admin_id')){
			return jsonSuccess('已登录');
		}else{
			return jsonError('未登录');
		}
	}
	
	/**
	 * 用户登录
	 * @param Request $request
	 * @throws Exception
	 * @return unknown
	 */
	public function adminLogin(Request $request)
	{
		$data = $request->post('');
		Db::startTrans();
		try {
			if(!$data['admin_name'])throw new Exception('请输入登录账号');
			if(!$data['admin_pwd'])throw new Exception('请输入登录密码');
			$admin = AdminUser::where(['admin_name' => $data['admin_name']])->find();
			if(!$admin)throw new Exception('账号不存在');
			if(md5($data['admin_pwd']) != $admin->admin_pwd)throw new Exception('密码不正确');
			session('admin_id',$admin->id);
			//添加日志
			Log::addLog(4, "管理员【{$admin->admin_real}】登录");
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('登录成功');
	}
	
	/**
	 * 退出登录
	 * @return unknown
	 */
	public function outLogin()
	{
		session('admin_id',null);
		return jsonSuccess('退出成功');
	}
}